/**
 * Copyright (C) Skywares Information Technology, LTD. 
 * All Rights Reserved.
 *
 * SysExceptionHandler.java created on 2020年2月2日 下午1:07:30 by Lyon Lu 
 */
package com.mvc.server.miaosha.exception;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mvc.server.result.CommonResult;
import com.mvc.server.result.ResultCode;

import lombok.extern.log4j.Log4j2;

/**
 * <pre>
 * Description:
 * 
 * @author Lyon Lu
 * @date 2020年2月2日 下午1:07:30
 *
 * </pre>
 */
@Log4j2
//@ControllerAdvice
//@ResponseBody
public class SysExceptionHandler {

	@ExceptionHandler(value = Exception.class)
	public CommonResult<Object> exceptionHandler(HttpServletRequest request, Exception e){
		
		log.error(e);
		
		if(e instanceof SysException) {
			SysException ex = (SysException)e;
			return CommonResult.error(ex.getResultCode());
		}
		else if(e instanceof BindException) {
			BindException ex = (BindException)e;
			List<ObjectError> errors = ex.getAllErrors();
			ObjectError error = errors.get(0);
			String msg = error.getDefaultMessage();
			return CommonResult.error(ResultCode.PARAM_BIND_ERROR.fillArgs(msg));
		}
		else {
			return CommonResult.error(ResultCode.SERVER_ERROR);
		}
	}
}
